package com.bookstore.dao;
import com.bookstore.model.User;
import com.bookstore.utils.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    /* 添加一个用户*/
    public void addUser(User user) throws SQLException {
        //1.获取到Query Runner
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        //2.sql语句
        String sql = "insert into user";
        sql+=" (username,PASSWORD,gender,email,telephone,introduce,activeCode,state,role,registTime)";
        sql+=" values(?,?,?,?,?,?,?,?,?,?)";
        //给values 赋值
//        Object[] prams = new Object[10];
//        prams[0]=
        //通过集合list实现
        List<Object> list = new ArrayList<Object>();
        list.add(user.getUsername());
        list.add(user.getTelephone());
        list.add(user.getGender());
        list.add(user.getEmail());
        list.add(user.getTelephone());
        list.add(user.getIntroduce());
        list.add(user.getActiveCode());
        list.add(user.getState());
        list.add(user.getRole());
        list.add(user.getRegistTime());

        //执行sql
        qr.update(sql,list.toArray());


    }
    public User findUserbyActivateCode(String ActivateCode) throws SQLException {
        //建立QueryRunner
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        //写sql语句
        String sql = "select * from user where activeCode=?";
        //执行qr
        return  qr.query(sql,new BeanHandler<User>(User.class),ActivateCode);
    }

    public void updateState(String ActivateCode) throws SQLException {
        //建立QueryRunner
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        //写sql语句
        String sql = "update user set state=1 where activeCode=?";
        //执行qr
        qr.update(sql,ActivateCode);
    }

}
